package module::carters_us::parser;
use Encode;

# ---------------------------------------------
# constructor
# Modify Log
# ---------------------------------------------
sub new {
    my $class = shift;
    my $self  = {};
    bless $self, $class;
    return $self;
}

# ---------------------------------------------
# parse one product detail page
# Modify Log
# ---------------------------------------------
sub parseAndgetInfo {
    my $this    = shift;
    my $url     = shift;
    my $pid     = shift;
    my $charSet = 'utf-8';
    my $data    = $main::filedata;
    my $content = $data->getPage( $url, $charSet );
    if ( !$content ) {

        # E300001 : Failed to get detail information of XXX.
        Log::Writer::setLog( "E300001", { 'URL' => $url } );
        return;
    }

    #    else {
    #        $content =~ s/<!--.*?-->//isg;
    #    }
    if ( $content =~ /This item is out of stock/ ) {

        # A300002: Some product is not instock,so this product page url is recorded.
        Log::Write::setLog( 'A300002', { 'URL' => $url } );
        return;
    }

    # defind properties about product
    my $time = new Date::Time->getGMT();
    my $description;
    my $price;
    my $salePrice;
    my $imageURL;
    my @idArray;
    my @sizes;
    my @colors;
    my %product;
    my $productName;

    # get name
    if ( $content =~ /class="productname"[^>]*>(.*?)<\//is ) {
        $productName = $1;
        $productName =~ s/<!--.*?-->//isg;
    }
    else {
        Log::Write::setLog( "E300002", { 'URL' => $url, 'POINT' => 'Product Name' } );
        return;
    }
    
    if($productName =~ /name="giftCardAmount"/is){
        return;
    }

    # get Description
    # Modify Begin Louise 14/10/2013 #.... ####
    if ( $content =~ m/<div class="descContainer">(.*?)<\/div>\s*<\/div>/is ) {
        $description = $1;
        $description =~ s/\t//isg;
        $description =~ s/\r/\n/isg;
        $description =~ s/\n+/\n/isg;
        $description =~ s/^\s+|\s+$//g;
        $description =~ s/^<.*?>/<ul>/;
        $description =~ s/<\/p>/<\/ul>/;
        if($description =~ /<div[^>]*>\s*<ul>/is){
        	$description =~ s/<div[^>]*>\s*//isg;
        }
        else{
        	$description =~ s/<div[^>]*>\s*/<ul>/isg;
        }
        $description =~ s/<ul>\s*<\/ul>//g;
        $description =~ s/<lil>/<li>/g;
        $description =~ s/<li>\s*<\/li>//g;
        $description =~ s/<li>\n<\/ul>/<\/li>\n<\/ul>/;
        $description =~ s/&quot;/\"/g;
    }
    # Modify End Louise 14/10/2013 #.... ####
    
    if ( !$description ) {
        $description = $productName;

        # Log::Write::setLog("E300002",{'URL'=>$url,'POINT'=>'Description'});
    }

    # get product id
    my %colorNameStyleHash;
    while ( $content =~ /"styleNo"\s*:\s*"([^"]+)"[^\}]*"color"\s*:\s*"([^"]+)"/isg ) {
        my $pid   = $1;
        my $cName = $2;

        # push @idArray, $pid;
        $colorNameStyleHash{$cName} = $pid;
    }

    # get Color and Size
    my $instock = 0;
    my %colors;
    my @prices;
    my @saleprices;

####get colorinfo
    my %imgUrlHash;
    my %imgSwatchHash;
    my $imgUrl;
    my $swatchUrl;
    my $colorName;
    my @instockColorName;

    my @colorNameArray;
    @colorNameArray = ( keys %colorNameStyleHash );
    foreach my $item (@colorNameArray) {
        my @oneColorSizeArray;
        while ( $content =~ /['"]$item['"]([^\[]+)avLevels/isg ) {
            my $temp1 = $1;
            my $size;
            my $flag = undef;
            if ( $temp1 =~ /["']size["']\s*:\s*["']([^"']+)["']/is ) {
                $size = $1;
            }
            if ( $temp1 =~ /inStock\s*:(.*?)\,/is ) {
                my $temp2 = $1;
                if ( $temp2 =~ /true/is ) {
                    $flag = 1;
                }
            }
            if ($flag) {
                push @oneColorSizeArray, $size;
            }
        }
        if ( scalar @oneColorSizeArray ) {
            push @instockColorName, $item;
            @sizes = ( @sizes, @oneColorSizeArray );
        }
    }

    @sizes = getUniqueItem(@sizes);

    # get color name ,image
    if ( $content =~ /\{\s*attributes(.*?)"size"/is ) {
        my $colorTxt = $1;
        while ( $colorTxt =~ /\{val:"([^"]+)"(.*?)\}\,/isg ) {
            $colorName = $1;
            my $oneTxt = $2;

            # push @colorNameArray, $colorName;
            if ( $oneTxt =~ /swatch:\s*["']([^"']+)["']/is ) {
                $swatchUrl = $1;
                if($swatchUrl =~ /null/is){
                    $swatchUrl = undef;
                }
            }
            if ( $oneTxt =~ /large\s*:.*?["']([^"']+)["']/is ) {
                $imgUrl = $1;
                if ( !$imageURL ) {
                    $imageURL = $imgUrl;
                }
            }

            my %color;
            $imgSwatchHash{$swatchUrl}++;
            $imgSwatchHash{$imgUrl}++;
            $imgUrlHash{$imgUrl}++;
            $imgUrlHash{$colorName}++;
            $color{'Name'} = $colorName;
            if ( $imgSwatchHash{$swatchUrl} > 1 ) {
                $color{'SwatchURL'} = undef;
            }
            else {
                $color{'SwatchURL'} = $swatchUrl;
            }
            if ( $imgUrlHash{$imgUrl} > 1 ) {
                $color{'ImageURL'}  = undef;
                $color{'SwatchURL'} = undef;
            }
            else {
                $color{'ImageURL'} = $imgUrl;
            }
            if ( !isHaveStringElement( \@instockColorName, $colorName ) ) {
                if ( $imgUrlHash{$colorName} > 1 ) {
                    $color{'Name'} = $colorName . ($imgUrlHash{$colorName}-1);
                    push @colors, \%color;
                }
                else {
                    push @colors, \%color;
                }
            }
        }
    }

    foreach my $item (@instockColorName) {
        push @idArray, $colorNameStyleHash{$item};
    }
    @idArray = getUniqueItem(@idArray);

    # get Product Id
    @idArray = sort @idArray;
    my $productId = shift @idArray;

    if ( !$productId ) {

        # E300002 : Failed get XXX field for page XXX.
        Log::Write::setLog( "E300002", { 'URL' => $url, 'POINT' => 'ProductId' } );
        return;
    }

    # get Price and SalePrice
    foreach my $item (@instockColorName) {
        my $style = $colorNameStyleHash{$item};
        while ( $content =~ /pricing(.*?)"styleNo"\s*:\s*"$style"/isg ) {
            my $tempTxt = $1;

            if ( $tempTxt =~ /MSRP\s*:\s*["']([^'"]+)["']/is ) {
                $price = $1;
            }
            if ( $tempTxt =~ /sale\s*:\s*["']([^'"]+)["']/is ) {
                $salePrice = $1;
            }
            if ( $price > 0 ) {
                push @prices, '$' . $price;
            }
            if ( $salePrice > 0 ) {
                push @saleprices, '$' . $salePrice;
            }
        }
    }
    if(!@prices && !@saleprices){
        my $priceTxt;
       if($content =~ /class="price"[^>]*>(.*?)<\/div>/is){
           $priceTxt = $1;
           my $price;
           my $salePrice;
           if($priceTxt =~ /MSRP\s*:\s*\$([ \d.]+)\s*</is){
               $price = $1;
                if ( $price > 0 ) {
                    push @prices, '$' . $price;
                }
           }
           if($priceTxt =~ /Price\s*:\s*\$([ \d.]+)\s*</is){
               $salePrice = $1;
               if ( $salePrice > 0 ) {
                    push @saleprices, '$' . $salePrice;
               }
           }
       }
    }
    
#    if(!@prices && !@saleprices){
#         my $priceTxt;
#        if($content =~/name="giftCardAmount"[^>]*>(.*?)<\/select>/is){
#            $priceTxt = $1;
#           my $price;
#           my $salePrice;
#           while($priceTxt =~ /value=["']([^'"]+)["']/isg){
#               $price = $1;
#                if ( $price > 0 ) {
#                    push @prices, '$' . $price;
#                }
#           }
##           if($priceTxt =~ /Price\s*:\s*\$([ \d.]+)\s*</is){
##               $salePrice = $1;
##               if ( $salePrice > 0 ) {
##                    push @saleprices, '$' . $salePrice;
##               }
##           }
#        }
#    }
#    $price     = getPriceOrSalePriceValue(@prices);
#    $salePrice = getPriceOrSalePriceValue(@saleprices);
    my @price2 =  getPriceAndSalePrice(\@prices,\@saleprices);
    $price     = $price2[0];
    $salePrice = $price2[1];

    if ($price =~ /\.(\d+)/is) {
        my $temp3 = $1;
        if(length($temp3)<2){
            $price =  $price.'0';
        }
    }
    if ($salePrice =~ /\.(\d+)/is) {
        my $temp3 = $1;
        if(length($temp3)<2){
            $salePrice =  $salePrice.'0';
        }
    }

    #    my $tempUrl = 'http://www.carters.com/on/demandware.store/Sites-Carters-Site/default/Product-GetVariants?pid='.$pid.'&format=json';
    #    my $tempcontent = $data -> getPage ( $tempUrl, $charSet );

    if ( !$price ) {
        # E300002 : Failed get XXX field for page XXX.
        Log::Write::setLog( "E300002", { 'URL' => $url, 'POINT' => 'Price' } );
        return;
    }
    # get ImageURL
    if ( !$imageURL ) {

        # E300002 : Failed get XXX field for page XXX.
        Log::Write::setLog( "E300002", { 'URL' => $url, 'POINT' => 'ImageURL' } );
        return;
    }

    # get ProductURL
    #    $url =~ s/$pid/$productId/is;

    # bulid Product
    %product = (
        'Name'        => $productName,
        'ProductId'   => $productId,
        'Description' => $description,
        'Price'       => $price,
        'SalePrice'   => $salePrice,
        #        'ProductURL'  => $url,
        'ImageURL' => $imageURL,
        'Size'     => \@sizes,
        'Color'    => \@colors,
        'Time'     => $time
    );
    return %product;
}

sub getUniqueItem {
    my @all = @_;
    my @only;
    my %count;
    @only = grep { ++$count{$_} < 2 } @all;
    return @only;
}

sub getPriceOrSalePriceValue {
    my @all = @_;
    my %hash2order;
    my $itemSize;
    @all      = getUniqueItem(@all);
    $itemSize = scalar @all;
    if ( $itemSize == 1 ) {
        return $all[0];
    }
    elsif ( $itemSize > 1 ) {
        foreach my $item (@all) {
            $item = trim_all_blank($item);
            my $temp = $item;
            $temp =~ /((\d|\.|\,){1,})/;
            $temp = $1;
            if ( $temp =~ /(,\d\d)$/is ) {
                my $last    = $1;
                my $newLast = $last;
                $newLast =~ s#,#.#is;
                $temp    =~ s/(,\d\d)$//is;
                $temp = $temp . $newLast;
            }
            $temp =~ s/[^0-9.]//isg;
            if ( !$hash2order{$temp} ) {
                $hash2order{$temp} = $item;
            }
        }
        my @hash;
        foreach my $key ( sort { $a <=> $b } keys %hash2order ) {
            push( @hash, $hash2order{$key} );
        }
        if ( scalar @hash > 1 ) {
            return $hash[0] . '-' . $hash[$#hash];
        }
        else {
            return $hash[0];
        }
    }
}

sub trim_all_blank {
    my $str = shift;
    $str =~ s/\s*//isg;
    return $str;
}

sub isHaveStringElement {
    my $array   = shift;
    my $element = shift;
    my @arrays  = @{$array};
    for my $arrayElement (@arrays) {
        if ( $arrayElement eq $element ) {
            return 0;
        }
    }
    return 1;
}


sub getPriceAndSalePrice {
    my $price     = shift;
    my $salePrice = shift;
    my @priceSet;
    if ($price) {
        $price = getPriceOrSalePriceValue(@$price);
    }
    if ($salePrice) {
        $salePrice = getPriceOrSalePriceValue(@$salePrice);
    }

    if ( $price && $salePrice ) {
        if ( $price eq $salePrice ) {
            if ( $price =~ /-/is ) {
            }
            else {
                $salePrice = undef;
            }
        }
    }
    elsif ( !$price && $salePrice or $price && !$salePrice ) {
        $price = $price ? $price : $salePrice;
        $salePrice = undef;
    }
    else {
        $price     = undef;
        $salePrice = undef;
    }

    push @priceSet, $price;
    push @priceSet, $salePrice;
    return @priceSet;
}


1;
